#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import logging.config
import os
import shutil
import sys
import yaml
import json


class Config:
    def __init__(self):
        self.theme = "cosmo"  # 默认主题
        self.reload()

    def _load_config(self):
        """
        从 config.yaml 加载配置。如果文件不存在，则生成默认配置文件。
        """
        # 获取应用程序的数据目录
        if getattr(sys, 'frozen', False):
            # 如果是打包后的环境
            app_dir = os.path.dirname(sys.executable)
        else:
            # 如果是开发环境
            app_dir = os.path.dirname(os.path.abspath(__file__))
        
        config_path = os.path.join(app_dir, "config.yaml")
        template_path = os.path.join(app_dir, "config-template.yaml")
    
        # 如果 config.yaml 不存在，且 config-template.yaml 存在，则拷贝
        if not os.path.exists(config_path) and os.path.exists(template_path):
            shutil.copyfile(template_path, config_path)
            print(f"已从 {template_path} 生成 {config_path}")
    
        if not os.path.exists(config_path):
            # 生成默认配置文件
            default_config = self.template_config_dict()
            with open(config_path, "w", encoding='utf-8') as f:
                yaml.dump(default_config, f, allow_unicode=True)
            return default_config
        else:
            with open(config_path, "r", encoding='utf-8') as f:
                return yaml.safe_load(f)

    def update(self, dict) -> None:
        """
        更新配置文件
        """
        print('Updating')
        yconfig = self._load_config()
        yconfig.update(dict)
        print("更新配置")
        
        # 获取正确的配置文件路径
        if getattr(sys, 'frozen', False):
            config_path = os.path.join(os.path.dirname(sys.executable), "config.yaml")
        else:
            config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.yaml")
        
        try:
            with open(config_path, "w", encoding="utf-8") as fp:
                yaml.dump(data=yconfig, stream=fp, allow_unicode=True)
                self.reload()
        except Exception as e:
            print(f"保存配置文件失败: {e}")

    def template_config_dict(self):
        """
        返回默认的配置模板字典。
        """
        return {
            "api_key": "",
            "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
            "model": "qwen-plus",
            "committer": "djs",
            "current_version": "1.0.4",
            "enhanced_mode": False,
            "max_length": "40960",
            "last_repo_path": "",  # 添加上次选择的仓库路径
            "commit_format": " 【提交人】： 【版本号】： 【提交类型】： 【提交描述】： 1.xxxxxxxxxxxxxxxx 2.xxxxxxxxxxxxxxxx 【修改内容】： 【修改文件】： ",
            "commit_standard": (
                "build：涉及构建相关的改动（如升级 npm 包、修改 webpack 配置等\n"
                "chore：构建过程或辅助工具的变更\n"
                "ci：持续集成相关的改动 docs：文档相关的变更\n"
                "feat：新增特性或功能\n"
                "fix：bug 修复 perf：性能相关改动 \n"
                "refactor：重构相关（非 bug、非新功能）\n"
                "revert：回滚 \n"
                "commit style：代码风格的调整，如格式化、空格等\n"
                "test：测试相关，包括新增测试或者更改已有测试"
            ),
            "theme": "cosmo",
            
            "vendor_urls": {
                "OpenAI": "https://api.openai.com/v1",
                "阿里通义": "https://dashscope.aliyuncs.com/compatible-mode/v1",
                "DeepSeek": "https://api.deepseek.com/v1",
                "自定义": ""
            },
            "mcp_server": {
                "host": "127.0.0.1",
                "port": 8000,
                "base_url": "http://127.0.0.1:8000"
            },
            "logging": {
                "disable_existing_loggers": False,
                "formatters": {
                    "error": {
                        "format": "%(asctime)s %(name)s %(levelname)s %(filename)s::%(funcName)s[%(lineno)d]:%(message)s"
                    },
                    "simple": {
                        "datefmt": "%Y-%m-%d %H:%M:%S",
                        "format": "%(asctime)s %(message)s"
                    }
                },
                "handlers": {
                    "console": {
                        "class": "logging.StreamHandler",
                        "formatter": "simple",
                        "level": "INFO",
                        "stream": "ext://sys.stdout"
                    },
                    "error_file_handler": {
                        "backupCount": 20,
                        "class": "logging.handlers.RotatingFileHandler",
                        "encoding": "utf8",
                        "filename": "error.log",
                        "formatter": "error",
                        "level": "ERROR",
                        "maxBytes": 10485760
                    },
                    "info_file_handler": {
                        "backupCount": 20,
                        "class": "logging.handlers.RotatingFileHandler",
                        "encoding": "utf8",
                        "filename": "info.log",
                        "formatter": "simple",
                        "level": "INFO",
                        "maxBytes": 10485760
                    }
                }
            }
        }



    def reload(self) -> None:
        '''
        将配置文件进行重新载入
        '''
        yconfig = self._load_config()
        self.committer = yconfig['committer']
        self.api_key = yconfig['api_key']
        self.base_url = yconfig['base_url']
        self.max_length = yconfig['max_length']
        self.model = yconfig['model']
        self.current_version = yconfig['current_version']
        self.commit_format=yconfig['commit_format']
        self.commit_standard=yconfig['commit_standard']
        self.enhanced_mode=yconfig['enhanced_mode']
        self.mcp_server=yconfig['mcp_server']
        # 加载模型厂商配置
        self.vendor_urls = yconfig.get('vendor_urls', {
            "OpenAI": "https://api.openai.com/v1",
            "阿里通义": "https://dashscope.aliyuncs.com/compatible-mode/v1",
            "DeepSeek": "https://api.deepseek.com/v1",
            "自定义": ""
        })
        self.theme = yconfig.get("theme", "cosmo")

        # 添加 MCP 服务器配置
        self.mcp_server = {
            'host': self.mcp_server.get('host', '127.0.0.1'),
            'port': self.mcp_server.get('port', 8000),
            'base_url': self.mcp_server.get('base_url', 'http://127.0.0.1:8000')
        }

        self.last_repo_path = yconfig.get('last_repo_path', '')  # 加载上次的仓库路径





    def getOriginConfig(self):
        '''
        读取yaml配置源文件
        '''
        pwd = os.path.dirname(os.path.abspath(__file__))
        try:
            with open(f"{pwd}/config.yaml", "r",encoding='utf-8') as fp:
                yfile = fp.read()
        except FileNotFoundError:
            shutil.copyfile(f"{pwd}/config.yaml.template", f"{pwd}/config.yaml")
            with open(f"{pwd}/config.yaml", "r",encoding='utf-8') as fp:
                yfile = fp.read()
        return yfile
    def getConfigPath(self):
        pwd = os.path.dirname(os.path.abspath(__file__))
        config_file_path = f"{pwd}/config.yaml"
        return config_file_path


